<template>
	<view>
		<view class="auth">
			<view class="auth-title" @click="sendMessage">输入短信验证码</view>
			<view class="auth-mobile">
				短信验证码至<text>{{mobile}}</text>
			</view>
			<view class="codes">
				<view v-for="item in config.count" :key="item.key">
					<input 
					type="number" 
					:password="false"  
					auto-fill="smsCode"
					:focus="currentFocus == item.index"
					@input="onInput"
					@tap="hanldeOpenKeyboard"
					@paste="handlePaste"  
					:class="{ active: currentFocus == item.index }"
					class="input"
					maxlength="6"  
					:value="code[item.index - 1]"
					/>
				</view>
				<!-- 添加隐藏的input用于接收粘贴 -->
				<input 
					type="text" 
					style="position: absolute; opacity: 0; width: 0; height: 0;"
					@input="handlePasteInput"
					ref="pasteInput"
					id="pasteInput"
				/>
			</view>
			<view class="auth-again">
				<text v-if="countdown > 0" class="time">{{countdown}}秒后重新发送</text>
				<text v-if="countdown == 0" @tap="resend">重新发送</text>
				<text v-if="countdown < 50">没有收到验证码？</text>
			</view>
		</view>
		<wanl-captcha ref="wanlCaptcha" />
		<!-- <wanl-keyboard :open="keyboardVisible" @number="inputCode" @delete="deleteCode" @empty="emptyCode"
			@close="keyboardVisible = false" /> -->
	</view>
</template>
<script>
	export default {
		data() {
			return {
				config: {
				count: [
					{ index: 1, key: 'valid-code-input-1' },
					{ index: 2, key: 'valid-code-input-2' },
					{ index: 3, key: 'valid-code-input-3' },
					{ index: 4, key: 'valid-code-input-4' },
					{ index: 5, key: 'valid-code-input-5' },
					{ index: 6, key: 'valid-code-input-6' }
				]
				},
				keyboardVisible: true,
				currentFocus: 1,
				mobile: '',
				code: Array(6).fill(''), // 初始化为空字符串数组
				style: {
				inputWidth: '40upx',
				inputHeight: '100upx'
				},
				countdown: 60,
				cTimer: null,
				event: '',
				pageroute: ''
			};
		},
		onLoad(options) {
			this.mobile = options.mobile;
			this.event = options.event;
			this.pageroute = options.url;
			this.sendMessage();
		},
		methods: {
			onInput(e) {
				const value = e.detail.value;
				// 处理长按粘贴的情况
				if (value.length === 6 && /^\d{6}$/.test(value)) {
					this.handleQuickInput(value);
				} else if (value.length === 1) {
					this.inputCode(value);
				}
			},
			// 处理快速输入（粘贴）
			handleQuickInput(fullCode) {
				if (fullCode.length === 6 && /^\d{6}$/.test(fullCode)) {
					this.code = fullCode.split('');
					this.currentFocus = 7; // 设置为超出范围，失去焦点
					this.login();
				}
			},
			// 处理粘贴事件
			handlePaste(e) {
				// 在小程序中，直接获取粘贴板内容
				uni.getClipboardData({
					success: (res) => {
						const pasteText = res.data.trim();
						if (pasteText.length === 6 && /^\d{6}$/.test(pasteText)) {
							this.handleQuickInput(pasteText);
						}
					}
				});
			},
			// 备用粘贴处理方法
			handlePasteInput(e) {
				const value = e.detail.value;
				if (value.length === 6 && /^\d{6}$/.test(value)) {
					this.handleQuickInput(value);
					// 清空隐藏输入框
					this.$nextTick(() => {
						const query = uni.createSelectorQuery().in(this);
						query.select('#pasteInput').node((res) => {
							if (res.node) {
								res.node.value = '';
							}
						}).exec();
					});
				}
			},
			// async 
			sendMessage() {
				// await
				uni.request({
					url: '/wanlshop/sms/send',
					method: 'POST',
					data: {
						event: this.event,
						mobile: this.mobile
					},
					success: res => {
						this.$wanlshop.msg('验证码发送成功');
						this.startTimer();
					},
					// 1.1.8升级
					complete: res => {
						if (res.data.code == 4) {
							this.$refs.wanlCaptcha.init({
								event: this.event,
								mobile: this.mobile
							}).then(() => {
								// 验证通过回调
								this.$wanlshop.msg('验证码发送成功');
								this.startTimer();
							}).catch(() => {
								uni.navigateBack({
									delta: 1
								});
							});
						}
					}
				});
			},
			// 修改 inputCode 方法以适应自动填充
			inputCode(e) {
				const value = typeof e === 'string' ? e : e.detail.value;
				
				// 如果是自动填充整个验证码
				if (value.length > 1) {
					const codes = value.split('').slice(0, 6);
					this.code = codes;
					this.currentFocus = codes.length + 1;
					if (codes.length === 6) {
						this.login();
					}
				} else {
					// 单个数字输入
					this.code[this.currentFocus - 1] = value;
					if (this.currentFocus == 6) {
						this.login();
					}
					if (this.currentFocus <= 6) {
						this.currentFocus++;
					}
				}
			},
			async login() {
				uni.showLoading();
				// 找回密码
				if (this.event == 'resetpwd') {
					this.$wanlshop.to(
						`resetpwd?mobile=${this.mobile}&captcha=${this.code.join("")}&url=${this.pageroute}`);
					uni.hideLoading();
				}
				// 找回支付密码
				if (this.event == 'forgetpaypwd') {
					this.$wanlshop.to(
						`forgetpaypwd?mobile=${this.mobile}&captcha=${this.code.join("")}&url=${this.pageroute}`);
					uni.hideLoading();
				}
				// 绑定手机号
				if (this.event == 'binding') {

				}
				// 验证码登录
				if (this.event == 'mobilelogin') {
					await uni.request({
						url: '/wanlshop/user/mobilelogin',
						method: 'POST',
						data: {
							mobile: this.mobile,
							captcha: this.code.join(""),
							client_id: uni.getStorageSync("wanlshop:chat_client_id") ? uni.getStorageSync(
								"wanlshop:chat_client_id") : null
						},
						success: res => {
							uni.hideLoading();
							// 中央控制总线
							this.$store.dispatch('user/login', res.data);
							this.$store.dispatch('cart/login');
							uni.reLaunch({
								url: decodeURIComponent(this.pageroute)
							});
						}
					});
				}
				// 用户注册
				if (this.event == 'register') {
					await uni.request({
						url: '/wanlshop/user/register',
						method: 'POST',
						data: {
							mobile: this.mobile,
							captcha: this.code.join(""),
							client_id: uni.getStorageSync("wanlshop:chat_client_id") ? uni.getStorageSync(
								"wanlshop:chat_client_id") : null,
							share_user_id: uni.getStorageSync("wanlshop:share_user_id") ?? 0
						},
						success: res => {
							uni.hideLoading();
							// 中央控制总线
							this.$store.dispatch('user/login', res.data);
							this.$store.dispatch('cart/login');
							this.$store.dispatch('chat/get');
							uni.reLaunch({
								url: decodeURIComponent(this.pageroute)
							});
						}
					});
				}
				this.currentFocus = 0;
				this.code = [];
			},
			deleteCode() {
				this.currentFocus--;
				this.code.splice(-1, 1);
			},
			emptyCode() {
				this.code = [];
				this.currentFocus = 0;
			},
			hanldeOpenKeyboard() {
				this.keyboardVisible = true;
			},
			startTimer() {
				if (this.cTimer == null) {
					this.cTimer = setInterval(() => {
						this.countdown--;
						if (this.countdown == 0) {
							this.clearTimer();
						}
					}, 1000)
				}
			},
			clearTimer() {
				clearInterval(this.cTimer);
				this.cTimer = null;
			},
			resend() {
				this.startTimer();
				this.code = [];
				this.currentFocus = 0;
				this.countdown = 60;
				this.sendMessage();
			}
		}
	};
</script>

<style>
	@import url("auth.css");
</style>